from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
from alibabacloud_videoenhan20200320.models import ReduceVideoNoiseAdvanceRequest
import random
from icecream import ic
import time
from threading import Thread
from time import sleep, ctime
import subprocess
import pymysql
import oss2 as oss
import requests
import os
import urllib
import urllib.request
import ssl
from urllib.request import urlopen
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from alibabacloud_videoenhan20200320.client import Client as srClient # pip install alibabacloud_videoenhan20200320 -i https://pypi.org/simple
from alibabacloud_videoenhan20200320.models import SuperResolveVideoAdvanceRequest
from time import sleep
from alibabacloud_viapi20230117.client import Client as gajrClient  # pip install alibabacloud_viapi20230117 -i https://pypi.org/simple
from alibabacloud_viapi20230117.models import GetAsyncJobResultRequest
from alibabacloud_videorecog20200320.client import Client as usClient  # pip install alibabacloud_videorecog20200320 -i https://pypi.org/simple
from alibabacloud_videorecog20200320.client import Client as spClient  # pip install alibabacloud_videorecog20200320 -i https://pypi.org/simple
from alibabacloud_videorecog20200320.client import Client as vcClient  # pip install alibabacloud_videorecog20200320 -i https://pypi.org/simple
from alibabacloud_mts20140618.client import Client as csClient  # pip install alibabacloud_videorecog20200320 -i https://pypi.org/simple
from alibabacloud_videorecog20200320.models import UnderstandVideoContentAdvanceRequest
from alibabacloud_videorecog20200320.models import SplitVideoPartsRequest
from alibabacloud_videorecog20200320.models import GenerateVideoCoverRequest
from alibabacloud_mts20140618.models import SubmitMediaCensorJobRequest
from alibabacloud_tea_util.client import Client as UtilClient
from viapi.fileutils import FileUtils
from alibabacloud_mts20140618 import models as mts_20140618_models
from alibabacloud_tea_util import models as util_models
# 导入requests包
import requests
import json
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer, BaseHTTPRequestHandler
import http.client
import json
from icecream import ic
import time

def get_time():
    return str(time.time())[:10]
    
def get_token():
    url = "https://auth-box.inspurcloud.cn/auth/realms/picp/protocol/openid-connect/token"
    data = {"grant_type":"password",
    "username":"inspurtest01",
    "password":"opOP@123?",
    "client_id":"bss-client",
    "response_type": "code id_token"}
    res = requests.post(url=url, data = data)#这里传入的data,是body里面的数据。params是拼接url时的参数
    return json.loads(res.text)['access_token']

def add_template(body, token): 
    body['timestamp'] = get_time()
    body['nonce'] = body['timestamp']
    conn = http.client.HTTPSConnection("service-box.inspurcloud.cn")
    payload = json.dumps(body)
    headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {}'.format(token)
    }
    conn.request("POST", "/regionsvc-region-box/mps/openapi/v1/transcode-templates", payload, headers)
    res = conn.getresponse()
    data = res.read()
    return data.decode("utf-8")

def delete_template(token, id):
    timestamp = get_time()
    conn = http.client.HTTPSConnection("service-box.inspurcloud.cn")
    payload = ''
    headers = {'Authorization': 'Bearer {}'.format(token)}
    url = "https://service-box.inspurcloud.cn/regionsvc-region-box/mps/openapi/v1/transcode-templates/{}?nonce={}&timestamp={}".format(id, timestamp, timestamp)
    # ic(url)
    # ic(token)
    conn.request("DELETE", url, payload, headers)
    res = conn.getresponse()
    data = res.read()
    return data.decode("utf-8")


def upload_to_oss(file_name):
    # 设置基本信息
    APIKey = 'MGNhNTBiOTctZjg4NC00NTk4LThjYmItNTk4ZmQzMDVhZjNm'
    APIKeySecrete = 'M2M5OTNiMzMtMjk5ZS00MmFiLWE0NjYtYzQ0NTAzZWU3YzI3'    
    EndPoint = 'oss.cn-north-3.inspurcloudoss.com'
    BucketName = 'media-test'
    ObjectName = file_name
    LocalFilePath = file_name
    auth = oss.Auth(APIKey, APIKeySecrete)
    bucket = oss.Bucket(auth, EndPoint, BucketName)
    with open(LocalFilePath, 'rb') as f:
        f.seek(0, os.SEEK_SET)
        cursor = f.tell()
        bucket.put_object(ObjectName, f)

def add_task_to_mysql(par):
    '''修改数据库中的任务'''
    conn=pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='',
        db='media_process',
        charset='utf8'
    )
    cursor=conn.cursor()
    sql = "insert into tasks(task_id,command,start_time,end_time,status,result) values('{}','{}','{}','{}','{}','{}');".format(*par.values())
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()

def alter_task_to_mysql(par):
    '''向数据库中添加任务记录'''
    conn=pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='',
        db='media_process',
        charset='utf8'
    )
    cursor=conn.cursor()
    sql = "update tasks set command = '{}',start_time = '{}',end_time = '{}',status = '{}',result = '{}' where task_id = '{}';"
    sql = sql.format(par['command'],par['start_time'],par['end_time'],par['status'],par['result'],par['task_id'])
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()
    
def task_thread(task_id, command, result_file):
    '''任务线程'''
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)  # 执行shell语句并定义输出格式
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['command'] = command
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par)
    re = p.wait()
    par['end_time'] = ctime()
    if re == 0: # 执行成功
        upload_to_oss(result_file)
        os.remove(result_file)
        par['status'] = 'succeed'
        par['result'] = 'https://media-test.oss.cn-north-3.inspurcloudoss.com/'+result_file
    else: # 执行失败
        par['status'] = 'failed'
    alter_task_to_mysql(par)

def video_interpolate(par):
    '''视频插帧'''
    # task_id:一个时间戳
    # create_status：成功，或失败（失败原因）
    # task_status：查询状态的链接
    # 参数检查
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    command = 'ffmpeg -i {} -filter:v "minterpolate=fps={}" -c:a copy {}.{}'.format(par['video'], par['fps'], task_id, file_format)
    ic(command)
    print(command)
    t1 = Thread(target=task_thread, args=(task_id, command, task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def audio_denoise(par):
    '''音频降噪'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['audio'][par['audio'].rfind('.')+1:]
    command = 'ffmpeg -i {} -af "highpass=f=200, lowpass=f=3000" {}.{}'.format(par['audio'], task_id, file_format)
    t1 = Thread(target=task_thread, args=(task_id, command, task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def audio_loudnorm(par):
    '''音频归一'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['audio'][par['audio'].rfind('.')+1:]
    command = 'ffmpeg -i {} -af loudnorm {}.{}'.format(par['audio'], task_id, file_format)
    t1 = Thread(target=task_thread, args=(task_id, command, task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_dctdnoiz(par):
    '''视频降噪'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    command = 'ffmpeg -i {} -vf dctdnoiz {}.{}'.format(par['video'], task_id, file_format)
    t1 = Thread(target=task_thread, args=(task_id, command, task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_super_resolution_thread(input_url, task_id, result_file):
    '''视频超分任务线程'''
    # 写数据库
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par) # -------------------------------------------------------------------------------------
    # 开始调用接口
    ssl._create_default_https_context = ssl._create_unverified_context # 全局取消证书验证
    urllib.request.urlretrieve(input_url, result_file) # 获取inspur的oss的文件
    # 接口配置
    config = Config(
        access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
        access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
        endpoint='videoenhan.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )
    # 新建任务
    img = open(result_file, 'rb')
    super_resolve_video_request = SuperResolveVideoAdvanceRequest()
    super_resolve_video_request.video_url_object = img
    super_resolve_video_request.bit_rate = 5
    runtime = RuntimeOptions()
    try:
        client = srClient(config)
        response = client.super_resolve_video_advance(super_resolve_video_request, runtime)
        RequestId = json.loads(str(response.body).replace("'",'"'))['RequestId']
        print(RequestId)
    except Exception as error:
        print(error)
        print(error.code)
    # 查询任务状态
    config = Config(
    access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
    access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
    endpoint='viapi.cn-shanghai.aliyuncs.com',
    region_id='cn-shanghai'
    )
    while True:
        sleep(3)
        get_async_job_result_request = GetAsyncJobResultRequest(
            job_id=RequestId
        )
        runtime = RuntimeOptions()
        try:
            client = gajrClient(config)
            response = client.get_async_job_result_with_options(get_async_job_result_request, runtime)
            Status = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Status']
            print(Status)
            if Status=='PROCESS_SUCCESS':
                Result = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Result']
                ResultURL = Result[Result.find(':')+1:-1]
                print(ResultURL)
                break
        except Exception as error:
            print(error)
            print(error.code)
    # 下载接口传回的文件
    img.close()
    urllib.request.urlretrieve(ResultURL, result_file) # 获取接口的oss的文件
    # 将文件上传到oss，删除本地文件
    upload_to_oss(result_file)
    os.remove(result_file)
    par['end_time'] = ctime()
    par['status'] = 'succeed'
    par['result'] = 'https://media-test.oss.cn-north-3.inspurcloudoss.com/'+result_file
    alter_task_to_mysql(par) # -------------------------------------------------------------------------------------------
    print(par)

def video_super_resolution(par):
    '''视频超分辨率'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    t1 = Thread(target=video_super_resolution_thread, args=(par['video'], task_id,  task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_denoise_thread(input_url, task_id, result_file):
    '''视频降噪任务线程'''
    # 写数据库
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par) # -------------------------------------------------------------------------------------
    # 开始调用接口
    ssl._create_default_https_context = ssl._create_unverified_context # 全局取消证书验证
    urllib.request.urlretrieve(input_url, result_file) # 获取inspur的oss的文件
    # 接口配置
    config = Config(
        access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
        access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
        endpoint='videoenhan.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )
    # 新建任务
    img = open(result_file, 'rb')
    reduce_video_noise_request = ReduceVideoNoiseAdvanceRequest()
    reduce_video_noise_request.video_url_object = img
    reduce_video_noise_request.bit_rate = 5
    runtime = RuntimeOptions()
    try:
        client = srClient(config)
        response = client.reduce_video_noise_advance(reduce_video_noise_request, runtime)
        RequestId = json.loads(str(response.body).replace("'",'"'))['RequestId']
        print(RequestId)
    except Exception as error:
        print(error)
        print(error.code)
    # 查询任务状态
    config = Config(
    access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
    access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
    endpoint='viapi.cn-shanghai.aliyuncs.com',
    region_id='cn-shanghai'
    )
    while True:
        sleep(3)
        get_async_job_result_request = GetAsyncJobResultRequest(
            job_id=RequestId
        )
        runtime = RuntimeOptions()
        try:
            client = gajrClient(config)
            response = client.get_async_job_result_with_options(get_async_job_result_request, runtime)
            Status = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Status']
            print(Status)
            if Status=='PROCESS_SUCCESS':
                Result = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Result']
                ResultURL = Result[Result.find(':')+1:-1]
                print(ResultURL)
                break
        except Exception as error:
            print(error)
            print(error.code)
    # 下载接口传回的文件
    img.close()
    urllib.request.urlretrieve(ResultURL, result_file) # 获取接口的oss的文件
    # 将文件上传到oss，删除本地文件
    upload_to_oss(result_file)
    os.remove(result_file)
    par['end_time'] = ctime()
    par['status'] = 'succeed'
    par['result'] = 'https://media-test.oss.cn-north-3.inspurcloudoss.com/'+result_file
    alter_task_to_mysql(par) # -------------------------------------------------------------------------------------------
    print(par)

def video_denoise(par):
    '''视频降噪'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    t1 = Thread(target=video_denoise_thread, args=(par['video'], task_id,  task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_understand_thread(input_url, task_id, result_file):
    '''视频理解任务线程'''
    # 写数据库
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par) # -------------------------------------------------------------------------------------
    # 下载文件
    ssl._create_default_https_context = ssl._create_unverified_context # 全局取消证书验证
    urllib.request.urlretrieve(input_url, result_file) # 获取inspur的oss的文件
    # 接口配置
    config = Config(
        access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
        access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
        endpoint='videorecog.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )
    # 新建任务
    understand_video_content_request = UnderstandVideoContentAdvanceRequest()
    stream = open(result_file, 'rb')
    understand_video_content_request.video_urlobject = stream
    runtime = RuntimeOptions()
    try:
        client = usClient(config)
        response = client.understand_video_content_advance(understand_video_content_request, runtime)
        print(response.body)
        RequestId = json.loads(str(response.body).replace("'",'"'))['RequestId']
        print(RequestId)
    except Exception as error:
        print(error)
        print(error.code)
    stream.close()
    # 查询任务状态
    config = Config(
    access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
    access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
    endpoint='viapi.cn-shanghai.aliyuncs.com',
    region_id='cn-shanghai'
    )
    while True:
        sleep(3)
        get_async_job_result_request = GetAsyncJobResultRequest(
            job_id=RequestId
        )
        runtime = RuntimeOptions()
        try:
            client = gajrClient(config)
            response = client.get_async_job_result_with_options(get_async_job_result_request, runtime)
            Status = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Status']
            print(Status)
            if Status=='PROCESS_SUCCESS':
                ic(response.body)
                Result = json.loads(str(response.body).replace('"','“').replace("'",'"'))['Data']['Result'].replace('“','"')
                ic(Result)
                Result = str(json.loads(Result)['tagInfo']).replace("'",'"')
                ic(Result)
                break
        except Exception as error:
            print(error)
            print(error.code)
    os.remove(result_file)
    par['end_time'] = ctime()
    par['status'] = 'succeed'
    par['result'] = Result
    alter_task_to_mysql(par) # -------------------------------------------------------------------------------------------
    ic(par)

def video_understand(par):
    '''视频理解'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    t1 = Thread(target=video_understand_thread, args=(par['video'], task_id,  task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_split_thread(input_url, task_id, result_file):
    '''视频拆条任务线程'''
    # 写数据库
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par) # -------------------------------------------------------------------------------------
    # 上传文件到接口
    file_utils = FileUtils("LTAI5t6GK5tGDsMU7jEGdEkM", "8H1pdFYccKdcDPciYKFtlZUsmCqnPM")
    oss_url = file_utils.get_oss_url(input_url, input_url[input_url.find('.')+1:], False)
    # 接口配置 # 新建任务
    config = Config(
        access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
        access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
        endpoint='videorecog.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )
    client = spClient(config)
    split_video_parts_request = SplitVideoPartsRequest(video_url=oss_url)
    runtime = RuntimeOptions()
    try:
        # 复制代码运行请自行打印 API 的返回值
        response = client.split_video_parts_with_options(split_video_parts_request, runtime)
        print(response.body)
        RequestId = json.loads(str(response.body).replace("'",'"'))['RequestId']
        print(RequestId)
    except Exception as error:
        # 如有需要，请打印 error
        UtilClient.assert_as_string(error.message)
    # 查询任务状态
    config = Config(
    access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
    access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
    endpoint='viapi.cn-shanghai.aliyuncs.com',
    region_id='cn-shanghai'
    )
    while True:
        sleep(3)
        get_async_job_result_request = GetAsyncJobResultRequest(
            job_id=RequestId
        )
        runtime = RuntimeOptions()
        try:
            client = gajrClient(config)
            response = client.get_async_job_result_with_options(get_async_job_result_request, runtime)
            Status = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Status']
            print(Status)
            if Status=='PROCESS_SUCCESS':
                ic(response.body)
                Result = json.loads(str(response.body).replace('"','“').replace("'",'"'))['Data']['Result'].replace('“','"')
                ic(Result)
                Result = str(json.loads(Result)["splitVideoPartResults"]).replace("'",'"')
                ic(Result)
                break
        except Exception as error:
            print(error)
            print(error.code)
    par['end_time'] = ctime()
    par['status'] = 'succeed'
    par['result'] = Result
    alter_task_to_mysql(par) # -------------------------------------------------------------------------------------------
    ic(par)

def video_split(par):
    '''视频拆条'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    t1 = Thread(target=video_split_thread, args=(par['video'], task_id,  task_id+'.'+file_format))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_cover_thread(input_url, task_id, result_file):
    '''视频封面任务线程'''
    # 写数据库
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par) # -------------------------------------------------------------------------------------
    # 上传文件到接口
    file_utils = FileUtils("LTAI5t6GK5tGDsMU7jEGdEkM", "8H1pdFYccKdcDPciYKFtlZUsmCqnPM")
    oss_url = file_utils.get_oss_url(input_url, input_url[input_url.find('.')+1:], False)
    ic(oss_url)
    # 接口配置 # 新建任务
    config = Config(
        access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
        access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
        endpoint='videorecog.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )
    client = vcClient(config)
    generate_video_cover_request = GenerateVideoCoverRequest(video_url=oss_url,is_gif=False)
    runtime = RuntimeOptions()
    try:
        # 复制代码运行请自行打印 API 的返回值
        response = client.generate_video_cover_with_options(generate_video_cover_request, runtime)
        print(response.body)
        RequestId = json.loads(str(response.body).replace("'",'"'))['RequestId']
        print(RequestId)
    except Exception as error:
        # 如有需要，请打印 error
        UtilClient.assert_as_string(error.message)
    # 查询任务状态
    config = Config(
    access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
    access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
    endpoint='viapi.cn-shanghai.aliyuncs.com',
    region_id='cn-shanghai'
    )
    while True:
        sleep(3)
        get_async_job_result_request = GetAsyncJobResultRequest(
            job_id=RequestId
        )
        runtime = RuntimeOptions()
        try:
            client = gajrClient(config)
            response = client.get_async_job_result_with_options(get_async_job_result_request, runtime)
            Status = json.loads(str(response.body).replace('"','').replace("'",'"'))['Data']['Status']
            print(Status)
            if Status=='PROCESS_SUCCESS':
                ic(response.body)
                Result = json.loads(str(response.body).replace('"','“').replace("'",'"'))['Data']['Result'].replace('“','"')
                ic(Result)
                ResultURL = json.loads(Result)['Outputs'][0]['ImageURL']
                ic(ResultURL)
                break
        except Exception as error:
            print(error)
            print(error.code)
    urllib.request.urlretrieve(ResultURL, result_file) # �~N��~O~V�~N��~O��~Z~Doss�~Z~D�~V~G件
    # ��~F�~V~G件��~J��| �~H�oss��~L�~H| �~Y��~\��~\��~V~G件
    upload_to_oss(result_file)
    os.remove(result_file)
    par['end_time'] = ctime()
    par['status'] = 'succeed'
    par['result'] = 'https://media-test.oss.cn-north-3.inspurcloudoss.com/'+result_file
    alter_task_to_mysql(par) # -------------------------------------------------------------------------------------------
    ic(par)

def video_cover(par):
    '''视频封面'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    t1 = Thread(target=video_cover_thread, args=(par['video'], task_id,  task_id+'.png'))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_censor_thread(input_url, task_id):
    '''视频审核任务线程'''
    # 写数据库
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par) # -------------------------------------------------------------------------------------
    # 上传文件到接口
    auth = oss.Auth('LTAI5t6GK5tGDsMU7jEGdEkM', '8H1pdFYccKdcDPciYKFtlZUsmCqnPM')
    bucket = oss.Bucket(auth, 'https://oss-cn-shanghai.aliyuncs.com', 'media-test-kang')
    file_form = input_url[input_url.rfind('.'):]
    bucket.put_object(task_id+file_form, requests.get(input_url))
    # 接口配置 # 新建任务
    config = Config(
        access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
        access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
        endpoint='mts.cn-shanghai.aliyuncs.com',
        # region_id='cn-shanghai'
    )
    client = csClient(config)
    input = '''{"Bucket":"media-test-kang","Location":"oss-cn-shanghai","Object":"'''+task_id+file_form+'''"}'''
    ic(input)
    video_censor_config = '''{
            "Scenes" : ["porn","terrorism","ad","live","logo","audio"],
            "OutputFile":{
                "Bucket": "media-test-kang",
                "Location": "oss-cn-shanghai",
                "Object": "example-{Count}.jpg"
            },
            "SaveType" : "abnormal",
            "BizType":"common"
        }'''
    submit_media_censor_job_request = SubmitMediaCensorJobRequest(
            input=input,
            pipeline_id='',
            video_censor_config=video_censor_config
        )
    runtime = RuntimeOptions()
    try:
        # 复制代码运行请自行打印 API 的返回值
        response = client.submit_media_censor_job_with_options(submit_media_censor_job_request, runtime)
        JobId = json.loads(str(response.body).replace("'",'"'))['JobId']
        ic(JobId)
    except Exception as error:
        # 如有需要，请打印 error
        UtilClient.assert_as_string(error.message)
        print(error)
    # 查询任务状态
    while True:
        sleep(3)
        config = Config(
            access_key_id='LTAI5t6GK5tGDsMU7jEGdEkM',
            access_key_secret='8H1pdFYccKdcDPciYKFtlZUsmCqnPM',
            endpoint='mts.cn-shanghai.aliyuncs.com'
        )
        client = csClient(config)
        query_media_censor_job_detail_request = mts_20140618_models.QueryMediaCensorJobDetailRequest(
            job_id=JobId
        )
        runtime = util_models.RuntimeOptions()
        try:
            response = client.query_media_censor_job_detail_with_options(query_media_censor_job_detail_request, runtime)
            Status = json.loads(str(response.body).replace("'",'"').replace('False', '"False"'))['MediaCensorJobDetail']['State']
            ic(Status)
            if Status == "Success":
                Result = json.loads(str(response.body).replace("'",'"').replace('False','""'))['MediaCensorJobDetail']['VensorCensorResult']['CensorResults']['CensorResult']
                Result = str(Result).replace("'",'"')
                break
        except Exception as error:
            UtilClient.assert_as_string(error.message)
            print(error)
    par['end_time'] = ctime()
    par['status'] = 'succeed'
    par['result'] = Result
    alter_task_to_mysql(par) # -------------------------------------------------------------------------------------------
    ic(par)

def video_censor(par):
    '''视频审核'''
    task_id = str(int(time.time()* 10000000))
    file_format = par['video'][par['video'].rfind('.')+1:]
    t1 = Thread(target=video_censor_thread, args=(par['video'], task_id))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def video_encrypt_thread(task_id, command, result_file, vkey):
    '''视频加密线程'''
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)  # 执行shell语句并定义输出格式
    par = {'task_id':'','command':'','start_time':'','end_time':'','status':'','result':''}
    par['task_id'] = task_id
    par['command'] = command
    par['start_time'] = ctime()
    par['status'] = 'processing'
    add_task_to_mysql(par)
    re = p.wait()
    par['end_time'] = ctime()
    if re == 0: # 执行成功
        upload_to_oss(result_file)
        os.remove(result_file)
        par['status'] = 'succeed'
        url = 'https://media-test.oss.cn-north-3.inspurcloudoss.com/'+result_file
        play = 'ffplay -i {} -decryption_key {}'.format(url,vkey)
        par['result']='{{"url":"{}","key":"{}","play":"{}"}}'.format(url,vkey,play)
    else: # 执行失败
        par['status'] = 'failed'
    alter_task_to_mysql(par)
    # print(par)

def video_encrypt(par):
    '''视频加密'''
    task_id = str(int(time.time()* 10000000))
    s1 = ''.join([random.choice("0123456789abcdef") for i in range(32)])
    s2 = ''.join([random.choice("0123456789abcdef") for i in range(32)])
    command = 'ffmpeg -i {} -vcodec copy -acodec copy -encryption_scheme cenc-aes-ctr -encryption_key {} -encryption_kid {} {}.mp4'.format(par['video'], s1, s2, task_id)
    t1 = Thread(target=video_encrypt_thread, args=(task_id, command, task_id+'.mp4', s1))
    t1.start()
    result = dict()
    result['task_id'] = task_id
    result['create_status'] = 'succeed'
    return result

def task_query(par):
    '''查询任务状态'''
    conn=pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='',
        db='media_process',
        charset='utf8'
    )
    cursor=conn.cursor()
    sql = "select * from tasks where task_id={};".format(par['task_id'])
    cursor.execute(sql)
    results = cursor.fetchone()
    try:
        result5 = json.loads(results[5])
    except Exception as error:
        result5 = results[5]
    results = {'task_id':results[0],'command':results[1],'start_time':results[2],'end_time':results[3],'status':results[4],'result':result5}
    cursor.close()
    conn.close()
    return results
class resquest_handler(BaseHTTPRequestHandler):
    def do_POST(self):
        # 获取并解析出参数
        command = self.path
        datas = self.rfile.read(int(self.headers['content-length']))
        parameters = json.loads(datas.decode())
        ic(parameters)
        if command.startswith('/audio_denoise'): # 音频降噪
            result = audio_denoise(parameters)
        elif command.startswith('/audio_loudnorm'): # 音频归一
            result = audio_loudnorm(parameters)
        elif command.startswith('/video_dctdnoiz'): # 视频降噪
            result = video_dctdnoiz(parameters)
        elif command.startswith('/video_denoise'): # 视频降噪
            result = video_denoise(parameters)
        elif command.startswith('/video_interpolate'): # 视频插帧
            result = video_interpolate(parameters)
        elif command.startswith('/video_super_resolution'): # 视频超分
            result = video_super_resolution(parameters)
        elif command.startswith('/video_understand'): # 视频理解
            result = video_understand(parameters)
        elif command.startswith('/video_encrypt'): # video encrypt
            result = video_encrypt(parameters)
        elif command.startswith('/video_split'): #video split
            result = video_split(parameters)
        elif command.startswith('/task_query'):# task query
            result = task_query(parameters)
        elif command.startswith('/video_cover'):# video cover
            result = video_cover(parameters)
        elif command.startswith('/video_censor'):# video censor
            result = video_censor(parameters)
        elif command.startswith('/alter_template'):
            token = get_token()
            # 删除原模板
            result1 = delete_template(token, parameters['id'])
            ic(result1)
            result1 = json.loads(result1)['message']
            # 增加模板
            result2 = add_template(parameters['data'], token)
            result2 = json.loads(result2)
            result = result2.copy()
            result2 = result2['message']
            result['message'] = '修改失败'
            if result1 == '删除成功' and result2 == '新增成功':
                result['message'] = '修改成功'
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(result).encode())

    def do_GET(self):
        command = self.path[:self.path.find('?')]
        if '#' in self.path:
            parameters = self.path[self.path.find('?')+1:self.path.rfind('#')]
        else:
            parameters = self.path[self.path.find('?')+1:]
        parameters = dict([i.split('=') for i in parameters.split('&')])
        if self.path.startswith('/video_interpolate'): # 视频插帧
            result = video_interpolate(parameters)
        elif self.path.startswith('/task_query'):
            result = task_query(parameters)
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(result).encode())

if __name__ == '__main__':
    server_address = ('0.0.0.0', 8888)
    httpd = HTTPServer(server_address, resquest_handler)
    print("Starting server, listen at: %s:%s" % server_address)
    httpd.serve_forever()